import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_scan_tool/db/api_provider.dart';
import 'package:flutter_scan_tool/db/dio_manage.dart';
import 'package:flutter_scan_tool/db/sp_provider.dart';
import 'package:flutter_scan_tool/models/storage_info.dart';
import 'package:flutter_scan_tool/models/tool.dart';

import 'tool_event.dart';
import 'tool_state.dart';


class ToolBloc extends Bloc<ToolEvent, ToolState> {
  SpProvider? sp;
  late List<ToolData> toolDataList=[];
  ToolBloc() : super(ToolState()) {
    sp = SpProvider.spProvider;
    on<ToolEvent>((event, emit) async {
      Map<String, dynamic> map = {};
      await prepareFetch(map, emit);
    });
    on<ToolLoadEvent>((event, emit) async {
      await prepareFetch(event.map, emit);
    });
  }

  Future<void> prepareFetch(
      Map<String, dynamic> map, Emitter<ToolState> emit) async {
    String storageStr = await sp!.getValue('storage');
    if (storageStr.isNotEmpty) {
      StorageInfo storageInfo = StorageInfo.fromJson(storageStr);
      List<String> toolKitList =
          storageInfo.toolKitList?.map((e) => e.id).toList()??[];
      map.putIfAbsent('toolKitList', () => toolKitList);
      await fetchTool(emit, map);
    }
  }

   int count=0;
  Future<void> fetchTool(
      Emitter<ToolState> emit, Map<String, dynamic> map) async {
    try {
      emit(ToolLoadProgress());
      var result = await ApiProvider.fetchToolList(map);
      var imageList=await ApiProvider.fetchToolImageList();
      toolDataList.clear();
      if(result.isNotEmpty){
        for(var item in result){
          var tempData= imageList.where((element) => element.toolName==item.toolName&&element.toolSpec==item.toolSpec).toList();
          if(tempData.isNotEmpty){
            item.imgUrl=tempData.first.toolUrl;
          }else{
            item.imgUrl="$baseUrl/files/tool.png";
          }
          toolDataList.add(item);
        }
      }
      if(map.containsKey("name")){
        result=result.where((element) => element.toolName.contains(map['name'])).toList();
      }
      if(map.containsKey("toolKits")){
        result=result.where((element) => element.lockerSerialNo==map['toolKits']).toList();
      }
      debugPrint("当前值1:$count");
      count++;
      debugPrint("当前值:$count");
      emit(ToolLoadSuccess(result));
    } catch (err) {
      debugPrint(err.toString());
      emit(ToolLoadFail());
    }
  }
}
